/**
* Created by duzi on 7/6/15.
*/

var customer = {
    $input: $('#customer'),
    model: function(id){
        var self = this;
        $.ajax({
            type: "GET",
            url: '/customers/' + id,
            contentType: 'application/json',
            success: function(response){
                var sp = self.$input.parent().find('span');
                if(response.customerId){
                    sp.css('color', 'red');
                }else{
                    sp.css('color', '');
                }
            }
        })
    },
    event: function(){
        var self = this;
        this.$input.on('keyup', function(e){
            this.value = this.value.replace(/[^\d]/g,'');

            if(!this.value){
                $(this).parent().find('span').css('color', '');
                return;
            }

            self.model(this.value);
        })
    }
};

var list = {
    $list: $('.enteritem .billList'),
    $sumPrice:$('.sumPrice'),
    $sumAmount:$('.sumAmount'),
    $submit: $('#billSubmit'),
    $table: $('#billTable tbody'),
    listModel: [],
    submitModel: function(customerId,billList ){
        var self = this;
        var $sumPrice = this.$sumPrice;
        var $sumAmount = this.$sumAmount;

        $.ajax({
            type: "POST",
            url: "/bills",
            data: JSON.stringify({customerId: customerId,items: billList}),
            contentType: 'application/json',
            success: function(response){
                product.info = '';
                self.listModel = [];
                alert('訂單提交成功！訂單號爲： '+response.id);
                self.submitView();
                self.getBillModel(response.id);
            }
        })
    },
    getBillModel: function(id){
        var self = this;
        $.ajax({
            type: "GET",
            url: "/bills/"  + id,
            contentType: 'application/json',
            success: function(response){
                var html = '';
                response.billItems.forEach(function(item,index){
                    html += $('#tmple-list').html()
                        .replace('{name}', item.product.productName)
                        .replace('{sum}', item.billItemSum)
                        .replace('{sumPrice}', item.billItemSumPrice)
                });

                self.$table.append(html).parent().css('display', 'block');
                $('#billId').html('(id='+ response.billId +')');
                $('#billBack').css('display', 'block');
            }
        })
    },
    submitView: function(){
        this.$list.empty();
        $('.enterInput').val('');
        this.$table.find('tr').remove();
    },
    listItemView: function(){
        var self = this;
        var info = this.listModel[this.listModel.length - 1];
        var html = $('#tmple-listItem').html().replace('{id}', info.productRef)
                                        .replace('{name}', product.info.productName)
                                        .replace('{sum}', info.sum)
                                        .replace("{sumPrice}", info.price)
                                        .replace("{listLength}", self.listModel.length - 1);
        this.$list.append(html);
    },
    addItem: function(info, amount){
        var $sumPrice = this.$sumPrice;
        var $sumAmount = this.$sumAmount;
        var sumPrice = (info.productPrice * amount);

        var date = new Date();

        this.listModel.push({
            createTime: date.getTime(),
            sum: amount,
            price: sumPrice,
            productRef: info.productId,
        });

        this.listItemView();
        $sumPrice.text(parseFloat($sumPrice.text())+sumPrice);
        $sumAmount.text(parseInt($sumAmount.text()) + parseInt(amount))
    },
    removeItem: function(id){
        product.info.productStock += this.listModel.amount;
        this.listModel[id] = null;
    },
    event: function(){
        var $sumPrice = this.$sumPrice;
        var $sumAmount = this.$sumAmount;
        var self = this;

        this.$list.on('click', '.delete-right', function(){
            var arrayId = $(this).data('id');
            $sumPrice.text(parseFloat($sumPrice.text()) - self.listModel[arrayId].price);
            $sumAmount.text(parseInt($sumAmount.text()) - self.listModel[arrayId].sum);
            self.removeItem(arrayId);
            $(this).parent().remove();
        });

        this.$submit.on('click', function(){
            if(!customer.$input.val()){
                alert('呼叫顧客號~');
                return;
            }
            self.listModel.forEach(function(item, index){
                if(item == null){
                    self.listModel.splice(index, 1);
                }
            });

            if(self.listModel.length == 0) return;

            $(this).css('display', 'none');
            self.submitModel(customer.$input.val(), self.listModel);
        })

        $('#billBack').on('click', function(){
            self.$table.parent().css('display', 'none');
            $('#billId').html('');
            $(this).css('display', 'none');
            self.$submit.css('display', '');
            self.$sumPrice.text('0');
            self.$sumAmount.text('0');
        });
    }
};

var product = {
    $infoInput: $('#product'),
    $amountInput: $('#amount'),
    $info:  $('#productInfo'),
    $noFound: $('.enteritem .notFoundInfo'),
    infoModel: function(id){
        var self = this;
        $.ajax({
            type: "GET",
            url: "/products/" + id,
            contentType: 'application/json',
            success: function(response){
                self.infoView(response);
                self.info = response;
            }
        })
    },
    infoView: function(response){
        if(!response.productId){
            this.$info.css('display', 'none');
            this.$noFound.css('display','');
            this.info = null;
            return;
        }
        var html = $('#tmple-product').html().replace('{id}', response.productId)
            .replace('{name}', response.productName)
            .replace('{price}', response.productPrice)
            .replace('{priceDes}',  response.productPrice)
            .replace('{stock}', response.productStock)
            .replace('{des}', response.productDes);

        this.$info.find('.answer').html(html);
        this.$info.css('display', 'block');
        this.$noFound.css('display','none');
    },
    event: function(){
        var self = this;
        this.$infoInput.on('keyup', function(e){
            this.value = this.value.replace(/[^\d]/g,'');

            if(!this.value){
                return;
            }

            self.infoModel(this.value);
        });

        this.$amountInput.on('keyup', function(e){
            this.value = this.value.replace(/[^\d]/g,'');

            if(!self.info){
                alert("searching or maybe it's not a correct product id");
            }

            if(this.value > self.info.productStock){
                alert('dont have so much~');
                return;
            }

            if(this.value && e.keyCode == 13 ){
                list.addItem(self.info, this.value);
                self.info.productStock -= this.value;
            }
        });
    }
}

customer.event();
product.event();
list.event();
